<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>web socket 测试</title>
</head>
<body>
 
<div style="width: 600px;height: 400px;">
    <p>服务器输出:</p>
    <div style="border: 1px solid #CCC;height: 300px;overflow: scroll" id="server-msg-container">
 
    </div>
    <p>
        <textarea id="inp-msg" style="height: 50px;width: 500px"></textarea>
        <input type="button" value="发送" id="send"><br/>
        选择图片： <input type="file" id="send-pic">
    </p>
</div>
 
<script type="application/javascript">
    var ws = new WebSocket("ws://127.0.0.1:8888/server/1231231?authorization=Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjFmYzgyNTRjLTUyMzgtNDIwNS04MzlhLTU4ZDRlZGYxZGY0YyJ9.5l5eF66xlGn0lIb9V1cSmRGCiEv7Q8xGnwe_iWVT1CYZk2pQdaGBxlrU08ly0CZgqmuK4F3I9X7Qa8zaHmg44A");
    ws.onopen = function (ev) {
      console.log("成功建立连接")
    };
    // 收到消息后回显
    // WebSocket可以传递String、ArrayBuffer和Blob三种数据类型
    ws.onmessage = function (ev) {
        console.info("onmessage", ev);
        var inpMsg = document.getElementById("server-msg-container");
        if (typeof ev.data === "string") {
            inpMsg.innerHTML += ev.data + "<br/>";
        } else {
            var result = ev.data;
            // 读取文件流
            var flagReader = new FileReader();
            // 将流解析成一个ArrayBuffer
            flagReader.readAsArrayBuffer(result);

            // blobToArrayBuffer(result).then((arrayBuffer) => {
            // console.log(arrayBuffer);
            // }).catch((error) => {
            // console.error(error);
            // });

            // 注册加载事件
            flagReader.onload = function () {

                var imageReader = new FileReader();
                imageReader.readAsDataURL(result);
                console.info("服务器返回的数据大小:", result.size);
                
                imageReader.onload = function (img) {

                    console.log(img.target.result)
                    var imgHtml = "<img src='" + img.target.result + "' style='width: 100px;height: 100px;'>";
                    inpMsg.innerHTML += imgHtml.replace("data:application/octet-stream;", "data:image/png;") + "<br />";
                    inpMsg.scroll(inpMsg.scrollWidth,inpMsg.scrollHeight);
                };
            }
        }
    };
    ws.onerror = function () {
        var inpMsg = document.getElementById("server-msg-container");
        inpMsg.innerHTML += "发生异常" + "<br/>";
    };
    ws.onclose = function () {
        var inpMsg = document.getElementById("server-msg-container");
        inpMsg.innerHTML += "webSocket 关闭" + "<br/>";
    };
 
    // 发送文字消息
    document.getElementById("send").addEventListener("click", function () {
        ws.send(document.getElementById("inp-msg").value);
    }, false);
 
    // 发送图片
    document.querySelector('#send-pic').addEventListener('change', function () {
        var files = this.files;
        if (files && files.length) {
            var file = files[0];
            var fileReader = new FileReader();
            fileReader.readAsArrayBuffer(file);
            fileReader.onload = function (e) {
                // 获取到文件对象
                var result = e.target.result;

                // 创建 ArrayBuffer
                const buffer = new ArrayBuffer(32  + result.byteLength);
                // 获取 ArrayBuffer 的视图
                const view = new DataView(buffer);
                // 设置数据
                view.setInt8(0, 1);
                // console.log(view.getInt8(0))
                view.setInt8(1, 249);
                // console.log(view.getInt8(1))
                console.log("图片大小："+result.byteLength)
                view.setInt32(2, 32+result.byteLength, true);
                view.setInt16(6, 1, true);
                // console.log(view.getInt16(6, true))
                // const code = "101864569864463716353101";
                const code = "555555555555555555555555";
                for (let i=0; i< code.length; i++) {
                    // 转换成ascii码
                    view.setInt8(8+i, code.charAt(i).charCodeAt());
                    // console.log(view.getInt8(7+i))
                }
                
                // 将 buffer2 的数据复制到新的 ArrayBuffer 对象中
                for (let i = 0; i < result.byteLength; i++) {
                    view.setUint8(32 + i, result[i]);
                }
                console.log(buffer)
                // 发送数据到服务器端
                ws.send(buffer)
            }
        }
    }, false);

    function concatArrayBuffer(buffer1, buffer2) {
        // 创建一个新的 ArrayBuffer 对象
        let newBuffer = new ArrayBuffer(buffer1.byteLength + buffer2.byteLength);
        
        // 创建一个 DataView 对象
        let dataView = new DataView(newBuffer);
        
        // 将 buffer1 的数据复制到新的 ArrayBuffer 对象中
        for (let i = 0; i < buffer1.byteLength; i++) {
            dataView.setUint8(i, buffer1[i]);
        }
        
        // 将 buffer2 的数据复制到新的 ArrayBuffer 对象中
        for (let i = 0; i < buffer2.byteLength; i++) {
            dataView.setUint8(buffer1.byteLength + i, buffer2[i]);
        }
        
        // 返回新的 ArrayBuffer 对象
        return newBuffer;
    }

    function blobToArrayBuffer(blob) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.readAsArrayBuffer(blob);
            reader.onload = function() {
                let arrayBuffer = reader.result;
                resolve(arrayBuffer);
            }
            reader.onerror = reject;
        });
    }

    // function resolve(result) {
    //     console.log("resolve")
    // }

    // function reject(result) {
    //     console.log("reject")
    // }
</script>
</body>
</html>